package com.cf.vo;


import com.cf.constant.EnumReturnCode;
import com.cf.mapper.BeanMapper;
import com.cf.util.SpringBeanUtil;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.util.List;
import java.util.Set;

/**
 * cf-game-ResponseVo
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/3/1 15:14
 */
@ApiModel(value = "对外统一封装类")
public class ResponseVo<T> {

    @ApiModelProperty(value = "状态码：0（正常），500（异常）,300（参数校验异常）,401（请登陆）,405（权限不足）,501（账户余额不足）")
    private Integer code;

    @ApiModelProperty(value = "消息")
    private String msg;

    @ApiModelProperty(value = "数据")
    private T data;

    public ResponseVo() {
    }

    public ResponseVo(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }


    public static ResponseVo success(Object data, String msg, Class targetType) {
        return new ResponseVo(EnumReturnCode.SUCCESS.getCode(), msg, convert(data, targetType));
    }

    public static ResponseVo fail(Object data, String msg, Class targetType) {
        return new ResponseVo(EnumReturnCode.ERROR.getCode(), msg, convert(data, targetType));
    }

    public static ResponseVo fail(Integer code, Object data, String msg, Class targetType) {
        return new ResponseVo(code, msg, convert(data, targetType));
    }


    public static ResponseVo success(Object data, String msg) {
        return success(data, msg, Object.class);
    }

    public static  ResponseVo fail(Object data, String msg) {
        return fail(data, msg, Object.class);
    }

    public static ResponseVo fail(Integer code, Object data, String msg) {
        return fail(code, data, msg, Object.class);
    }

    private static Object convert(Object data, Class targetType) {
        if (targetType == null || Object.class.equals(targetType) || data == null)
            return data;
        if (data instanceof Set) {
            return SpringBeanUtil.getBean(BeanMapper.class).mapAsSet((Iterable) data, targetType);
        } else if (data instanceof List) {
            return SpringBeanUtil.getBean(BeanMapper.class).mapAsList((Iterable) data, targetType);
        } else {
            return SpringBeanUtil.getBean(BeanMapper.class).map(data, targetType);
        }
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }


}
